



<!DOCTYPE html>
<html lang="zh-CN">
  <head><meta name="generator" content="Hexo 3.9.0">
    <title>自定义指令 — Vue.js</title>
    <meta charset="utf-8">
    <meta name="description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="alternate" hreflang="x-default" href="https://vuejs.org/v2/guide/custom-directive.html">
    <link rel="alternate" hreflang="zh" href="https://cn.vuejs.org/v2/guide/custom-directive.html">
    <link rel="alternate" hreflang="ja" href="https://jp.vuejs.org/v2/guide/custom-directive.html">
    <link rel="alternate" hreflang="ru" href="https://ru.vuejs.org/v2/guide/custom-directive.html">
    <link rel="alternate" hreflang="ko" href="https://kr.vuejs.org/v2/guide/custom-directive.html">
    <link rel="alternate" hreflang="pt-BR" href="https://br.vuejs.org/v2/guide/custom-directive.html">
    <link rel="alternate" hreflang="fr" href="https://fr.vuejs.org/v2/guide/custom-directive.html">
    <link rel="alternate" hreflang="es" href="https://es.vuejs.org/v2/guide/custom-directive.html">

    <meta property="og:type" content="article">
    <meta property="og:title" content="自定义指令 — Vue.js">
    <meta property="og:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta property="og:image" content="https://cn.vuejs.org/images/logo.png">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="自定义指令 — Vue.js">
    <meta name="twitter:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="twitter:image" content="https://cn.vuejs.org/images/logo.png">

    <link rel="apple-touch-icon" sizes="57x57" href="/vue2/images/icons/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/vue2/images/icons/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/vue2/images/icons/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/vue2/images/icons/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/vue2/images/icons/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/vue2/images/icons/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/vue2/images/icons/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/vue2/images/icons/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/vue2/images/icons/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="/vue2/images/icons/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/vue2/images/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="/vue2/images/icons/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/vue2/images/icons/favicon-16x16.png">
    <meta name="msapplication-TileImage" content="/images/icons/ms-icon-144x144.png">
    <link rel="icon" href="/vue2/images/logo.svg">

    <meta name="msapplication-TileColor" content="#4fc08d">
    <meta name="theme-color" content="#4fc08d">

    <meta name="msapplication-config" content="browserconfig.xml">
    <link rel="manifest" href="/vue2/manifest.json">

    <!-- <link href="https://fonts.gstatic.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com" rel="preconnect" crossorigin> -->

    <!-- <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600|Roboto Mono&display=swap" rel="stylesheet"> -->
    <!-- <link href="https://fonts.googleapis.com/css?family=Dosis:500&text=Vue.js&display=swap" rel="stylesheet"> -->

    <link href="//code.bdstatic.com/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- main page styles -->
    <link rel="stylesheet" href="/vue2/css/page.css">

    <!-- this needs to be loaded before guide's inline scripts -->
    <script src="/vue2/js/vue.js"></script>

    

    <script>
      Vue.config.productionTip = false
      window.PAGE_TYPE = "guide"
    </script>

    <!-- ga -->
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-46852172-3', 'cn.vuejs.org');
      ga('send', 'pageview');
    </script>

    <!-- vimeo analytics -->
    <!-- <script type="text/javascript" defer="defer" src="https://extend.vimeocdn.com/ga/72160148.js"></script> -->
</head>
  <body class="docs">

    

    <div id="mobile-bar">
      <a class="menu-button"></a>
      <a class="logo" href="/"></a>
    </div>
    <div>
  <div id="v3-banner">
    <span class="hidden-sm">非官方文档，仅为个人学习使用，查看官方文档请移步</span><a href="https://cn.vuejs.org/" target="_blank">这里</a>。
  </div>

  <header id="header">
    <a id="logo" href="/vue2/">
      <img src="/vue2/images/logo.svg" alt="vue logo">
      <span>Vue.js</span>
    </a>
    <ul id="nav">
      <li>
  <form id="search-form">
    <input type="text" id="search-query-nav" class="search-query st-default-search-input" aria-label="搜索">
  </form>
</li>
<li class="nav-dropdown-container learn">
  <a class="nav-link current">学习</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>文档</h4></li>
    <li>
      <ul>
        <li><a href="/vue2/v2/guide/" class="nav-link current">教程</a></li>
        <li><a href="/vue2/v2/api/" class="nav-link">API</a></li>
        <li><a href="/vue2/v2/style-guide/" class="nav-link">风格指南</a></li>
        <li><a href="/vue2/v2/examples/" class="nav-link">示例</a></li>
        <li><a href="/vue2/v2/cookbook/" class="nav-link">Cookbook</a></li>
      </ul>
    </li>
    <li><h4>视频教程</h4></li>
    <li>
      <ul>
        <li>
          <a href="https://www.vuemastery.com/courses/" class="nav-link" target="_blank" rel="sponsored noopener">
            Vue Mastery (英文)
          </a>
        </li>
        <li>
          <a href="https://vueschool.io/?friend=vuejs&utm_source=Vuejs.org&utm_medium=Link&utm_content=Navbar%20Dropdown" class="nav-link" target="_blank" rel="sponsored noopener">
            Vue School (英文)
          </a>
        </li>
        <!-- start: special logic for cn -->
        <li>
          <a href="https://learning.dcloud.io/" class="nav-link" target="_blank" rel="sponsored noopener">
            DCloud 视频教程
          </a>
        </li>
        <!-- end: special logic for cn -->
      </ul>
    </li>
  </ul>
</li>

<li class="nav-dropdown-container ecosystem">
  <a class="nav-link">生态系统</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>帮助</h4></li>
    <li><ul>
      <li><a href="https://forum.vuejs.org/" class="nav-link" target="_blank" rel="noopener">论坛</a></li>
      <li><a href="https://chat.vuejs.org/" class="nav-link" target="_blank" rel="noopener">聊天室</a></li>
      <li><a href="https://events.vuejs.org/meetups/" class="nav-link" target="_blank" rel="noopener">聚会</a></li>
    </ul></li>
    <li><h4>工具</h4></li>
    <li>
      <ul>
        <li><a href="https://github.com/vuejs/vue-devtools" class="nav-link" target="_blank" rel="noopener">Devtools</a></li>
        <li><a href="https://cli.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue CLI</a></li>
        <li><a href="https://vue-loader.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Loader</a></li>
      </ul>
    </li>
    <li><h4>核心插件</h4></li>
    <li><ul>
      <li><a href="https://router.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Router</a></li>
      <li><a href="https://vuex.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vuex</a></li>
      <li><a href="https://ssr.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue 服务端渲染</a></li>
    </ul></li>
    <li><h4>信息</h4></li>
    <li><ul>
      <li><a href="https://news.vuejs.org" class="nav-link" target="_blank" rel="noopener">周刊</a></li>
      <li><a href="https://github.com/vuejs/vue/projects/6" class="nav-link" target="_blank" rel="noopener">Roadmap</a></li>
      <li><a href="https://events.vuejs.org/" class="nav-link" target="_blank" rel="noopener">活动</a></li>
      <li><a href="https://twitter.com/vuejs" class="nav-link" target="_blank" rel="noopener">Twitter</a></li>
      <li><a href="https://medium.com/the-vue-point" class="nav-link" target="_blank" rel="noopener">博客</a></li>
      <li><a href="https://vuejobs.com/?ref=vuejs" class="nav-link" target="_blank" rel="noopener">工作</a></li>
      <li><a href="https://dev.to/t/vue" class="nav-link" target="_blank" rel="noopener">DEV 社区</a></li>
    </ul></li>
  </ul>
</li>

<li>
  <a href="/vue2/v2/guide/team.html" class="nav-link team">团队</a>
</li>
<li class="nav-dropdown-container resources">
  <a href="#" class="nav-link">资源列表</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="/vue2/resources/partners.html" class="nav-link">合作伙伴</a></li>
    <li><a href="/vue2/resources/themes.html" class="nav-link">主题</a></li>
    <li><a href="https://github.com/vuejs/awesome-vue" class="nav-link" target="_blank" rel="noopener">Awesome Vue</a></li>
    <li><a href="https://awesomejs.dev/for/vue/" class="nav-link" target="_blank" rel="noopener">浏览和 Vue 相关的包</a></li>
  </ul>
</li>

<!-- <li>
  <a href="/vue2/partners" class="nav-link ">Partners</a>
</li> -->
<li class="nav-dropdown-container support-vue">
  <a href="/support-vuejs/" class="nav-link">支持 Vue</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="/support-vuejs/#One-time-Donations" class="nav-link">一次性赞助</a></li>
    <li><a href="/support-vuejs/#Recurring-Pledges" class="nav-link">周期性赞助</a></li>
    <!-- start: special logic for cn -->
    <li><a href="https://www.smallsticker.com/%E8%B4%B4%E7%BA%B8/vue.html" rel="noopener" class="nav-link">贴纸</a></li>
    <li><a href="https://osholic.com/?utm_source=vue&utm_medium=dropdown" rel="noopener" class="nav-link">周边</a></li>
    <!-- end: special logic for cn -->
    <li><a href="https://vue.threadless.com" target="_blank" rel="noopener" class="nav-link">T 恤商店</a></li>
  </ul>
</li>

<li class="nav-dropdown-container language">
  <a class="nav-link">多语言</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="https://vuejs.org/v2/guide/custom-directive.html" class="nav-link">English</a></li>
    <li><a href="https://jp.vuejs.org/v2/guide/custom-directive.html" class="nav-link">日本語</a></li>
    <li><a href="https://ru.vuejs.org/v2/guide/custom-directive.html" class="nav-link">Русский</a></li>
    <li><a href="https://kr.vuejs.org/v2/guide/custom-directive.html" class="nav-link">한국어</a></li>
    <li><a href="https://br.vuejs.org/v2/guide/custom-directive.html" class="nav-link">Português</a></li>
    <li><a href="https://fr.vuejs.org/v2/guide/custom-directive.html" class="nav-link">Français</a></li>
    <li><a href="https://vi.vuejs.org/v2/guide/custom-directive.html" class="nav-link">Tiếng Việt</a></li>
    <li><a href="https://es.vuejs.org/v2/guide/custom-directive.html" class="nav-link">Español</a></li>
    <li><a href="https://docs.vuejs.id/v2/guide/custom-directive.html" class="nav-link">Bahasa Indonesia</a></li>
  </ul>
</li>

<!-- start: special logic for cn -->
<li><a href="https://github.com/vuejs/cn.vuejs.org/" target="_blank" class="nav-link contribute">参与翻译</a></li>
<!-- end: special logic for cn -->

    </ul>
  </header>
</div>

    
      <div id="main" class="fix-sidebar">
        
  

<div class="sidebar">
  <div class="sidebar-inner">
    
    <div class="list">
      <div id="sidebar-sponsors-special">
  <div class="main-sponsor">
    <!-- start: special logic for cn -->
    <span>特别赞助商</span>
    <div>
    <a href="http://www.dcloud.io/?hmsr=vuejsorg&hmpl=&hmcu=&hmkw=&hmci=" target="_blank" rel="sponsored noopener" class="logo">
      <img id="s-dcloud" alt="dcloud">
      <script>
      (function(){
        var el = document.getElementById("s-dcloud");
        var adImg = null;
        var altImg = "/vue2/images/dcloud2.png";
        var img = "/vue2/images/dcloud1.png";
        el.src = adImg || (altImg && Math.random() >= 0.5 ? altImg : img);
      })()
      </script>
    </a>
    </div>
    <div>
    <a href="https://authing.cn/welcome?from=vuejs" target="_blank" rel="sponsored noopener" class="logo">
      <img id="s-authing" alt="authing">
      <script>
      (function(){
        var el = document.getElementById("s-authing");
        var adImg = null;
        var altImg = null;
        var img = "/vue2/images/authing.svg";
        el.src = adImg || (altImg && Math.random() >= 0.5 ? altImg : img);
      })()
      </script>
    </a>
    </div>
    <div>
    <a href="https://qingfuwu.cn?utm_campaign=TR_eSJH7nqW&utm_content=&utm_medium=Web&utm_source=CH_53OxwryD&utm_term=" target="_blank" rel="sponsored noopener" class="logo">
      <img id="s-qingfuwu" alt="qingfuwu">
      <script>
      (function(){
        var el = document.getElementById("s-qingfuwu");
        var adImg = null;
        var altImg = null;
        var img = "/vue2/images/qingfuwu.svg";
        el.src = adImg || (altImg && Math.random() >= 0.5 ? altImg : img);
      })()
      </script>
    </a>
    </div>
    <!-- end: special logic for cn -->
  </div>
</div>
<!--
<div id="sidebar-sponsors-platinum-left">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/retool.png" alt="Retool">
    </a>
    <a href="https://passionatepeople.io/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/passionate_people.png" alt="Passionate People">
    </a>
    <a href="https://www.storyblok.com" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/storyblok.png" alt="Storyblok">
    </a>
    <a href="https://ionicframework.com/vue?utm_source=partner&utm_medium=referral&utm_campaign=vuesponsorship&utm_content=vuedocs" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/ionic.png" alt="Ionic">
    </a>
    <a href="https://nuxtjs.org/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/nuxt.png" alt="Nuxt">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/vue2/support-vuejs">
    成为赞助者
  </a>
</div>

-->

      
        <h2>
          
          教程
          
            <select class="version-select">
              <option value="v3">3.x</option>
              <option value="SELF" selected>2.x</option>
              <option value="v1">1.0</option>
              <option value="012">0.12</option>
              <option value="011">0.11</option>
            </select>
          
        </h2>
        <ul class="menu-root">
  
    
    
      
        <li><h3>基础</h3></li>
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/installation.html" class="sidebar-link">安装</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/index.html" class="sidebar-link">介绍</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/instance.html" class="sidebar-link">Vue 实例</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/syntax.html" class="sidebar-link">模板语法</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/computed.html" class="sidebar-link">计算属性和侦听器</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/class-and-style.html" class="sidebar-link">Class 与 Style 绑定</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/conditional.html" class="sidebar-link">条件渲染</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/list.html" class="sidebar-link">列表渲染</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/events.html" class="sidebar-link">事件处理</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/forms.html" class="sidebar-link">表单输入绑定</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/components.html" class="sidebar-link">组件基础</a>
    </li>
  
    
    
      
      
        <li><h3>深入了解组件</h3></li>
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/components-registration.html" class="sidebar-link">组件注册</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/components-props.html" class="sidebar-link">Prop</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/components-custom-events.html" class="sidebar-link">自定义事件</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/components-slots.html" class="sidebar-link">插槽</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/components-dynamic-async.html" class="sidebar-link">动态组件 & 异步组件</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/components-edge-cases.html" class="sidebar-link">处理边界情况</a>
    </li>
  
    
    
      
      
      
        <li><h3>过渡 & 动画</h3></li>
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/transitions.html" class="sidebar-link">进入/离开 & 列表过渡</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/transitioning-state.html" class="sidebar-link">状态过渡</a>
    </li>
  
    
    
      
      
      
      
        <li><h3>可复用性 & 组合</h3></li>
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/mixins.html" class="sidebar-link">混入</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/custom-directive.html" class="sidebar-link current">自定义指令</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/render-function.html" class="sidebar-link">渲染函数 & JSX</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/plugins.html" class="sidebar-link">插件</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/filters.html" class="sidebar-link">过滤器</a>
    </li>
  
    
    
      
      
      
      
      
        <li><h3>工具</h3></li>
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/single-file-components.html" class="sidebar-link">单文件组件</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/testing.html" class="sidebar-link">测试</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/typescript.html" class="sidebar-link">TypeScript 支持</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/deployment.html" class="sidebar-link">生产环境部署</a>
    </li>
  
    
    
      
      
      
      
      
      
        <li><h3>规模化</h3></li>
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/routing.html" class="sidebar-link">路由</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/state-management.html" class="sidebar-link">状态管理</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/ssr.html" class="sidebar-link">服务端渲染</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/security.html" class="sidebar-link">安全</a>
    </li>
  
    
    
      
      
      
      
      
      
      
        <li><h3>内在</h3></li>
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/reactivity.html" class="sidebar-link">深入响应式原理</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
        <li><h3>迁移</h3></li>
      
      
    
    <li>
      <a href="/vue2/v2/guide/migration.html" class="sidebar-link">从 Vue 1.x 迁移</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/migration-vue-router.html" class="sidebar-link">从 Vue Router 0.7.x 迁移</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/migration-vuex.html" class="sidebar-link">从 Vuex 0.6.x 迁移到 1.0</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
        <li><h3>更多</h3></li>
      
    
    <li>
      <a href="/vue2/v2/guide/comparison.html" class="sidebar-link">对比其他框架</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/join.html" class="sidebar-link">加入 Vue.js 社区</a>
    </li>
  
    
    
      
      
      
      
      
      
      
      
      
    
    <li>
      <a href="/vue2/v2/guide/team.html" class="sidebar-link">认识团队</a>
    </li>
  
</ul>

      
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-right">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/retool.png" alt="Retool">
    </a>
    <a href="https://passionatepeople.io/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/passionate_people.png" alt="Passionate People">
    </a>
    <a href="https://www.storyblok.com" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/storyblok.png" alt="Storyblok">
    </a>
    <a href="https://ionicframework.com/vue?utm_source=partner&utm_medium=referral&utm_campaign=vuesponsorship&utm_content=vuedocs" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/ionic.png" alt="Ionic">
    </a>
    <a href="https://nuxtjs.org/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/vue2/images/nuxt.png" alt="Nuxt">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/vue2/support-vuejs">
    成为赞助者
  </a>
</div>


-->


<div class="content guide with-sidebar custom-directive-guide">
  <p class="tip warning v3-warning">
    您在浏览的是 v2.x 及更早版本的文档。v3.x 的文档<a href="https://wangyubina.github.io/vue3/">在这里</a>。
  </p>

  
    
      
<div id="ad">
  <!-- start: special logic for cn -->
  <div class="wwads-cn wwads-vertical" data-id="53" style="max-width: 200px"></div>
  <script type="text/javascript" src="https://cdn.wwads.cn/js/makemoney.js" async></script>
  <!-- end: special logic for cn -->
  <!-- <script
    async
    type="text/javascript"
    src="//cdn.carbonads.com/carbon.js?serve=CEBDT27Y&placement=vuejsorg"
    id="_carbonads_js"
  ></script> -->
</div>


    
  
  
    <h1>自定义指令</h1>
  

  <!-- start: special logic for cn -->
  <!-- start: special logic for cn -->
<!-- <div class="ad-pagetop">
  <a href="http://www.vueshop.com.cn/index.php?http_referer=vuejs" target="_blank" rel="noopener noreferrer">
    <span class="name">VUEshop</span>
    <span class="description">中国免费商城系统 - 搜豹商城系统 - 免费50小时 Vue 视频教程</span>
    <span class="action">立即查看 &gt;</span>
  </a>
</div> -->
<!-- end: special logic for cn -->

  <!-- end: special logic for cn -->

  
    <h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><div class="vueschool"><a href="https://vueschool.io/lessons/create-vuejs-directive?friend=vuejs" target="_blank" rel="sponsored noopener" title="Free Vue.js Custom Directives lesson">Watch a free video lesson on Vue School</a></div>

<p>除了核心功能默认内置的指令 (<code>v-model</code> 和 <code>v-show</code>)，Vue 也允许注册自定义指令。注意，在 Vue2.0 中，代码复用和抽象的主要形式是组件。然而，有的情况下，你仍然需要对普通 DOM 元素进行底层操作，这时候就会用到自定义指令。举个聚焦输入框的例子，如下：</p>

<div id="simplest-directive-example" class="demo">
  <input v-focus>
</div>
<script>
Vue.directive('focus', {
  inserted: function (el) {
    el.focus()
  }
})
new Vue({
  el: '#simplest-directive-example'
})
</script>

<p>当页面加载时，该元素将获得焦点 (注意：<code>autofocus</code> 在移动版 Safari 上不工作)。事实上，只要你在打开这个页面后还没点击过任何内容，这个输入框就应当还是处于聚焦状态。现在让我们用指令来实现这个功能：</p>
<pre><code class="hljs js"><span class="hljs-comment">// 注册一个全局自定义指令 `v-focus`</span>
Vue.directive(<span class="hljs-string">'focus'</span>, &#123;
  <span class="hljs-comment">// 当被绑定的元素插入到 DOM 中时……</span>
  <span class="hljs-attr">inserted</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el</span>) </span>&#123;
    <span class="hljs-comment">// 聚焦元素</span>
    el.focus()
  &#125;
&#125;)</code></pre>
<p>如果想注册局部指令，组件中也接受一个 <code>directives</code> 的选项：</p>
<pre><code class="hljs js">directives: &#123;
  <span class="hljs-attr">focus</span>: &#123;
    <span class="hljs-comment">// 指令的定义</span>
    <span class="hljs-attr">inserted</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el</span>) </span>&#123;
      el.focus()
    &#125;
  &#125;
&#125;</code></pre>
<p>然后你可以在模板中任何元素上使用新的 <code>v-focus</code> property，如下：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">v-focus</span>&gt;</span></code></pre>
<h2 id="钩子函数"><a href="#钩子函数" class="headerlink" title="钩子函数"></a>钩子函数</h2><p>一个指令定义对象可以提供如下几个钩子函数 (均为可选)：</p>
<ul>
<li><p><code>bind</code>：只调用一次，指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。</p>
</li>
<li><p><code>inserted</code>：被绑定元素插入父节点时调用 (仅保证父节点存在，但不一定已被插入文档中)。</p>
</li>
<li><p><code>update</code>：所在组件的 VNode 更新时调用，<strong>但是可能发生在其子 VNode 更新之前</strong>。指令的值可能发生了改变，也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)。</p>
</li>
</ul>
<p class="tip">我们会在<a href="./render-function.html#虚拟-DOM">稍后</a>讨论<a href="./render-function.html">渲染函数</a>时介绍更多 VNodes 的细节。</p>

<ul>
<li><p><code>componentUpdated</code>：指令所在组件的 VNode <strong>及其子 VNode</strong> 全部更新后调用。</p>
</li>
<li><p><code>unbind</code>：只调用一次，指令与元素解绑时调用。</p>
</li>
</ul>
<p>接下来我们来看一下钩子函数的参数 (即 <code>el</code>、<code>binding</code>、<code>vnode</code> 和 <code>oldVnode</code>)。</p>
<h2 id="钩子函数参数"><a href="#钩子函数参数" class="headerlink" title="钩子函数参数"></a>钩子函数参数</h2><p>指令钩子函数会被传入以下参数：</p>
<ul>
<li><code>el</code>：指令所绑定的元素，可以用来直接操作 DOM。</li>
<li><code>binding</code>：一个对象，包含以下 property：<ul>
<li><code>name</code>：指令名，不包括 <code>v-</code> 前缀。</li>
<li><code>value</code>：指令的绑定值，例如：<code>v-my-directive=&quot;1 + 1&quot;</code> 中，绑定值为 <code>2</code>。</li>
<li><code>oldValue</code>：指令绑定的前一个值，仅在 <code>update</code> 和 <code>componentUpdated</code> 钩子中可用。无论值是否改变都可用。</li>
<li><code>expression</code>：字符串形式的指令表达式。例如 <code>v-my-directive=&quot;1 + 1&quot;</code> 中，表达式为 <code>&quot;1 + 1&quot;</code>。</li>
<li><code>arg</code>：传给指令的参数，可选。例如 <code>v-my-directive:foo</code> 中，参数为 <code>&quot;foo&quot;</code>。</li>
<li><code>modifiers</code>：一个包含修饰符的对象。例如：<code>v-my-directive.foo.bar</code> 中，修饰符对象为 <code>{ foo: true, bar: true }</code>。</li>
</ul>
</li>
<li><code>vnode</code>：Vue 编译生成的虚拟节点。移步 <a href="../api/#VNode-接口">VNode API</a> 来了解更多详情。</li>
<li><code>oldVnode</code>：上一个虚拟节点，仅在 <code>update</code> 和 <code>componentUpdated</code> 钩子中可用。</li>
</ul>
<p class="tip">除了 <code>el</code> 之外，其它参数都应该是只读的，切勿进行修改。如果需要在钩子之间共享数据，建议通过元素的 <a href="https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLElement/dataset" target="_blank" rel="noopener"><code>dataset</code></a> 来进行。</p>

<p>这是一个使用了这些 property 的自定义钩子样例：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"hook-arguments-example"</span> <span class="hljs-attr">v-demo:foo.a.b</span>=<span class="hljs-string">"message"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<pre><code class="hljs js">Vue.directive(<span class="hljs-string">'demo'</span>, &#123;
  <span class="hljs-attr">bind</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el, binding, vnode</span>) </span>&#123;
    <span class="hljs-keyword">var</span> s = <span class="hljs-built_in">JSON</span>.stringify
    el.innerHTML =
      <span class="hljs-string">'name: '</span>       + s(binding.name) + <span class="hljs-string">'&lt;br&gt;'</span> +
      <span class="hljs-string">'value: '</span>      + s(binding.value) + <span class="hljs-string">'&lt;br&gt;'</span> +
      <span class="hljs-string">'expression: '</span> + s(binding.expression) + <span class="hljs-string">'&lt;br&gt;'</span> +
      <span class="hljs-string">'argument: '</span>   + s(binding.arg) + <span class="hljs-string">'&lt;br&gt;'</span> +
      <span class="hljs-string">'modifiers: '</span>  + s(binding.modifiers) + <span class="hljs-string">'&lt;br&gt;'</span> +
      <span class="hljs-string">'vnode keys: '</span> + <span class="hljs-built_in">Object</span>.keys(vnode).join(<span class="hljs-string">', '</span>)
  &#125;
&#125;)

<span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#hook-arguments-example'</span>,
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">message</span>: <span class="hljs-string">'hello!'</span>
  &#125;
&#125;)</code></pre>

<div id="hook-arguments-example" v-demo:foo.a.b="message" class="demo"></div>
<script>
Vue.directive('demo', {
  bind: function (el, binding, vnode) {
    var s = JSON.stringify
    el.innerHTML =
      'name: '       + s(binding.name) + '<br>' +
      'value: '      + s(binding.value) + '<br>' +
      'expression: ' + s(binding.expression) + '<br>' +
      'argument: '   + s(binding.arg) + '<br>' +
      'modifiers: '  + s(binding.modifiers) + '<br>' +
      'vnode keys: ' + Object.keys(vnode).join(', ')
  }
})
new Vue({
  el: '#hook-arguments-example',
  data: {
    message: 'hello!'
  }
})
</script>

<h3 id="动态指令参数"><a href="#动态指令参数" class="headerlink" title="动态指令参数"></a>动态指令参数</h3><p>指令的参数可以是动态的。例如，在 <code>v-mydirective:[argument]=&quot;value&quot;</code> 中，<code>argument</code> 参数可以根据组件实例数据进行更新！这使得自定义指令可以在应用中被灵活使用。</p>
<p>例如你想要创建一个自定义指令，用来通过固定布局将元素固定在页面上。我们可以像这样创建一个通过指令值来更新竖直位置像素值的自定义指令：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"baseexample"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Scroll down the page<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">v-pin</span>=<span class="hljs-string">"200"</span>&gt;</span>Stick me 200px from the top of the page<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<pre><code class="hljs js">Vue.directive(<span class="hljs-string">'pin'</span>, &#123;
  <span class="hljs-attr">bind</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el, binding, vnode</span>) </span>&#123;
    el.style.position = <span class="hljs-string">'fixed'</span>
    el.style.top = binding.value + <span class="hljs-string">'px'</span>
  &#125;
&#125;)

<span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#baseexample'</span>
&#125;)</code></pre>
<p>这会把该元素固定在距离页面顶部 200 像素的位置。但如果场景是我们需要把元素固定在左侧而不是顶部又该怎么办呢？这时使用动态参数就可以非常方便地根据每个组件实例来进行更新。</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"dynamicexample"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Scroll down inside this section ↓<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">v-pin:</span>[<span class="hljs-attr">direction</span>]=<span class="hljs-string">"200"</span>&gt;</span>I am pinned onto the page at 200px to the left.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<pre><code class="hljs js">Vue.directive(<span class="hljs-string">'pin'</span>, &#123;
  <span class="hljs-attr">bind</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el, binding, vnode</span>) </span>&#123;
    el.style.position = <span class="hljs-string">'fixed'</span>
    <span class="hljs-keyword">var</span> s = (binding.arg == <span class="hljs-string">'left'</span> ? <span class="hljs-string">'left'</span> : <span class="hljs-string">'top'</span>)
    el.style[s] = binding.value + <span class="hljs-string">'px'</span>
  &#125;
&#125;)

<span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#dynamicexample'</span>,
  <span class="hljs-attr">data</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
    <span class="hljs-keyword">return</span> &#123;
      <span class="hljs-attr">direction</span>: <span class="hljs-string">'left'</span>
    &#125;
  &#125;
&#125;)</code></pre>
<p>结果：</p>

<iframe height="200" style="width: 100%;" class="demo" scrolling="no" title="Dynamic Directive Arguments" src="//codepen.io/team/Vue/embed/rgLLzb/?height=300&theme-id=32763&default-tab=result" frameborder="no" allowtransparency="true" allowfullscreen="true">
  查看 <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a> 上 Vue
  (<a href="https://codepen.io/Vue" target="_blank" rel="noopener">@Vue</a>) 的例子 <a href="https://codepen.io/team/Vue/pen/rgLLzb/" target="_blank" rel="noopener">Dynamic Directive Arguments</a>.
</iframe>

<p>这样这个自定义指令现在的灵活性就足以支持一些不同的用例了。</p>
<h2 id="函数简写"><a href="#函数简写" class="headerlink" title="函数简写"></a>函数简写</h2><p>在很多时候，你可能想在 <code>bind</code> 和 <code>update</code> 时触发相同行为，而不关心其它的钩子。比如这样写：</p>
<pre><code class="hljs js">Vue.directive(<span class="hljs-string">'color-swatch'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el, binding</span>) </span>&#123;
  el.style.backgroundColor = binding.value
&#125;)</code></pre>
<h2 id="对象字面量"><a href="#对象字面量" class="headerlink" title="对象字面量"></a>对象字面量</h2><p>如果指令需要多个值，可以传入一个 JavaScript 对象字面量。记住，指令函数能够接受所有合法的 JavaScript 表达式。</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">v-demo</span>=<span class="hljs-string">"&#123; color: 'white', text: 'hello!' &#125;"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<pre><code class="hljs js">Vue.directive(<span class="hljs-string">'demo'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el, binding</span>) </span>&#123;
  <span class="hljs-built_in">console</span>.log(binding.value.color) <span class="hljs-comment">// =&gt; "white"</span>
  <span class="hljs-built_in">console</span>.log(binding.value.text)  <span class="hljs-comment">// =&gt; "hello!"</span>
&#125;)</code></pre>

  
  
    <div class="guide-links">
      
      
        <span>← <a href="/vue2/v2/guide/mixins.html">混入</a></span>
      
      
      
        <span style="float: right;"><a href="/vue2/v2/guide/render-function.html">渲染函数 & JSX</a> →</span>
      
    </div>
  
  <div class="footer">
      <script src="//m.servedby-buysellads.com/monetization.js" type="text/javascript"></script>
<div id="bsa-native"></div>
<script>
_bsa.init('custom', 'CKYD62QM', 'placement:vuejsorg',
  {
    target: '#bsa-native',
    template: '<a class="native-box" href="##statlink##"><div class="native-sponsor">Sponsor</div><div class="native-text"><strong>##company##</strong> — ##description##</div></a>'
  }
);
</script>


    发现错误？想参与编辑？
    <a href="https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/guide/custom-directive.md" rel="noopener" target="_blank">
      在 GitHub 上编辑此页！
    </a>
    <!-- Deployed on
    <a href="https://url.netlify.com/HJ8X2mxP8" rel="noopener" target="_blank">
      Netlify
    </a>. -->
  </div>
</div>

      </div>
      <script src="/vue2/js/smooth-scroll.min.js"></script>
    

    <!-- main custom script for sidebars, version selects etc. -->
    <script src="/vue2/js/css.escape.js"></script>
    <script src="/vue2/js/common.js"></script>

    <!-- search -->
    <link href="//code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="/vue2/css/search.css">
    <script src="//code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.js"></script>
    <script>
    [
      '#search-query-nav',
      '#search-query-sidebar',
      '#search-query-menu'
    ].forEach(function (selector) {
      if (!document.querySelector(selector)) return
      // search index defaults to v2
      var match = window.location.pathname.match(/^\/(v\d+)/)
      var version = match ? match[1] : 'v2'
      docsearch({
      appId: 'BH4D9OD16A',
      apiKey: '5638280abff9d207417bb03be05f0b25',
      indexName: 'vuejs_cn2',
      inputSelector: selector,
      algoliaOptions: { facetFilters: ["version:" + version] },
      autocompleteOptions: { hint: false, appendTo: 'body'}
      })
    })
    </script>
  </body>
</html>
